/**
 * @author lei2jun
 */

import get from '@network/get'
import names from '@/assets/libs/names'
import { SET_TAB } from './appShell/common'

export const SET_LIST = 'SET_LIST'

/**
 * 用于生成独立的 tab 数据保存
 */
const tabSeeder = () => {
  let list = {}
  Object.keys(names).forEach(key => {
    list[key] = {
      name: names[key],
      page: 1,
      loading: false,
      data: []
    }
  })
  return list
}

export const state = () => {
  return {
    list: {
      ...tabSeeder()
    },

    /**
     * 每页数量
     * @type {Number}
     */
    limit: 30,

    /**
     * 是否渲染 Markdown
     * @type {Boolean}
     */
    mdrender: true
  }
}

export const mutations = {
  /**
   * 
   * @param {Object} state 模块的 state 对象
   * @param {Object} payload {tab, data}
   */
  [SET_LIST](state, payload) {
    state.list[`${payload.type}`].data = [
      ...state.list[`${payload.type}`].data, 
      ...payload.data
    ]
  }
};

export const getters = {
  /**
   * 获取全局 tab
   * 
   * @param {Object} state 模块 state 对象
   * @param {Object} getters 模块 getters 对象
   * @param {Object} rootState 根 state 对象
   */
  currentTab(state, getters, rootState) {
    return rootState.appShell.common.currentTab
  }
}
export const actions = {
    /**
     * 首次获取数据
     */
    getList({commit, dispatch, state, getters}, tab) {
      commit(`appShell/common/${SET_TAB}`, tab, {root: true});

      const type = getters.currentTab

      if (state.list[`${type}`].data.length > 0) return;
      if (['all', 'good', 'share', 'ask', 'job', 'dev'].indexOf(type) === -1) return;
      dispatch('getMore')
    },

    /**
     * 用于加载更多数据
     */
    async getMore({commit, state, getters}) {
      const type = getters.currentTab

      if (!state.list[`${type}`] || state.list[`${type}`].loading) return;

      state.list[`${type}`].loading = true
      const res = await get('topics', {
        page: state.list[`${type}`].page++,
        tab: type,
        limit: state.limit,
        mdrender: state.mdrender, 
      })
      state.list[`${type}`].loading = false
      commit(SET_LIST, {type, data: res.data.data});
    }
};